package com.smart.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.EnumSet;

import java.util.Iterator;


import org.junit.Test;


import com.smart.service.util.Logging;

public class Control {
	
	/** A Constant LOGGER. */
	private static final Logging LOGGER = Logging
			.getLogger(Control.class.getName());
	
	enum PROCESS{
		CLIENT_HSQLDB("org.hsqldb.util.DatabaseManager -url jdbc:hsqldb:hsql://127.0.0.1:55000 -user sa"),
		HSQLDB("org.hsqldb.Server -port 55000 -database SmartWebService/database/smartwebservice -dbname.0 smartwebservice"); 
		
		private String nome;
		PROCESS(String name){
			nome = name;
		}
	}

	@Test
	public void stop() throws Exception {
		LOGGER.debug("STOP ");
		EnumSet<PROCESS> set = EnumSet.allOf(PROCESS.class);
		for (Iterator<PROCESS> iterator = set.iterator(); iterator.hasNext();) {
			PROCESS process = iterator.next();
			LOGGER.debug("PROCESS \t" + process.name() );
			String processId = getProcessId(process);
            if (processId != null) {
            	LOGGER.debug("ENCERRANDO\t" + process.name() );
                killProcess(processId);
                LOGGER.debug("ENCERRADO\t" + process.name());
            }else{
            	LOGGER.debug("INATIVO \t" + process.name());
            }
		}
    }

    private static String getProcessId(PROCESS process) throws Exception {
        // usa o programa jps para determinar o id do processo
        ProcessBuilder processBuilder = new ProcessBuilder("jps", "-l", "-m");
        Process jpsProcess = processBuilder.start();
        BufferedReader in = new BufferedReader(new InputStreamReader(jpsProcess.getInputStream()));
        String line;
        String processId = null;
        while ((line = in.readLine()) != null) {
            if (line.indexOf(process.nome) >= 0) {
                processId = line.substring(0, line.indexOf(' ')).trim();
                break;
            }
        }
        jpsProcess.waitFor();
        return processId;
    }

    /**
     * Encerra o processo com o identificador informado. Utiliza o comando
     * necessÃ¡rio para encerrar o programa de acordo com o sistema operacional.
     *
     * @param processId
     *            identificador do processo a ser eliminado
     * @throws Exception
     *             Caso ocorra algum erro na chamada do comando de encerrar o
     *             processo do sistema operacional.
     */
    private synchronized static void killProcess(String processId) throws Exception {
    	LOGGER.debug("KILL PROCESS " + processId);    	
        String[] killCommand;
        if (isWindows()) {
            killCommand = new String[]{"taskkill", "/PID", "/F", processId};
        } else {
            killCommand = new String[]{"kill", processId};
        }
        killCommand = new String[]{"taskkill", "/PID", "/F", processId};
        ProcessBuilder processBuilder = new ProcessBuilder(killCommand);
        Process killProcess = processBuilder.start();
        killProcess.waitFor();
    }
    
    private static boolean isWindows() {
        return File.separatorChar == '\\';
    }



}
